import { useRef, useState } from "react";

export function useTimer() {
  const timer = useRef<number | null>(null);
  const startTime = useRef<number>(0);
  const elapsedTime = useRef<number>(0);
  const [formatTime, setFormatTime] = useState<string>("00:00");

  const start = () => {
    if (timer.current) clearInterval(timer.current);
    startTime.current = Date.now() - elapsedTime.current;
    timer.current = setInterval(() => {
      elapsedTime.current = Date.now() - startTime.current;
      if (elapsedTime.current < 36e5) {
        setFormatTime(
          new Date(elapsedTime.current).toISOString().substr(14, 5)
        );
      } else {
        setFormatTime(
          new Date(elapsedTime.current).toISOString().substr(11, 8)
        );
      }
    }, 1000);
  };

  const pause = () => {
    if (timer.current) {
      clearInterval(timer.current);
      timer.current = null;
    }
  };

  const reset = () => {
    pause();
    elapsedTime.current = 0;
    startTime.current = 0;
    setFormatTime("00:00");
  };

  return {
    formatTime,
    start,
    pause,
    reset,
  };
}
